import React from 'react';
import { Icon, message } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { netUrl } from '../../config';
import { reloadAuthorized } from './Authorized';
import request from './request';

let loginStatus = '';
try {
  loginStatus =
    document.cookie && window.sessionStorage ? sessionStorage.getItem('antd-pro-authority') : '';
} catch (e) {
  message.error(e.toString());
}
if (!loginStatus || loginStatus === 'guest') {
  // 用户必须要先登录才能使用本系统
  reloadAuthorized();
  const loginPage = '#/user/login';
  if (document.location.hash !== loginPage) {
    document.location.hash = loginPage;
  }
}

moment.locale('zh-cn');

// 工具集
const tools = {
  // 获取今天的日期字符串
  funcToday(incTime = false, date = new Date()) {
    const yy = date.getFullYear();
    let mm = date.getMonth() + 1;
    let dd = date.getDate();

    mm = mm < 10 ? '0' + mm : mm;
    dd = dd < 10 ? '0' + dd : dd;

    let str = yy + '-' + mm + '-' + dd;

    if (incTime) {
      let hh = date.getHours();
      let m2 = date.getMinutes();

      hh = hh < 10 ? '0' + hh : hh;
      m2 = m2 < 10 ? '0' + m2 : m2;

      str += ' ' + hh + ':' + m2;
    }

    return str;
  },
  // 获取当前时间
  funcNow(hour = false, zero = true) {
    const d = new Date();
    let hh = d.getHours();
    let mm = d.getMinutes();
    let ss = d.getSeconds();

    if (zero) {
      hh = hh < 10 ? '0' + hh : hh;
      mm = mm < 10 ? '0' + mm : mm;
      ss = ss < 10 ? '0' + ss : ss;
    }

    let str = hh;

    if (!hour) str += ':' + mm + ':' + ss;

    return str;
  },
  // 获取今年元旦
  funcGetYYYY0101() {
    const d = new Date();
    const yy = d.getFullYear();
    return yy + '-01-01';
  },
  // 获取本月月初
  funcGetYYYYMM01() {
    const d = new Date();
    const yy = d.getFullYear();
    let mm = d.getMonth() + 1;
    mm = mm < 10 ? '0' + mm : mm;
    return yy + '-' + mm + '-01';
  },
  // 获取明年
  funcGetNextYear() {
    const d = new Date();
    const yy = d.getFullYear() + 1;
    let mm = d.getMonth() + 1;
    let dd = d.getDate();
    mm = mm < 10 ? '0' + mm : mm;
    dd = dd < 10 ? '0' + dd : dd;
    return yy + '-' + mm + '-' + dd;
  },
  // 获取下月
  funcGetNextMonth(dateStr = '') {
    const d = dateStr === '' ? new Date() : new Date(dateStr);
    let yy = d.getFullYear();
    let mm = d.getMonth() + 2;
    if (mm === 13) {
      mm = 1;
      yy += 1;
    }
    mm = mm < 10 ? '0' + mm : mm;
    return yy + '-' + mm + '-01';
  },
  // 获取月底
  funcGetLastMonthDay(dateStr = tools.funcToday()) {
    let yy = parseInt(dateStr.substr(0, 4), 10);
    let mm = parseInt(dateStr.substr(5, 2), 10);
    mm += 1;
    if (mm === 13) {
      mm = 1;
      yy += 1;
    }
    if (mm < 10) mm = '0' + mm;
    let date1 = yy + '-' + mm + '-01';
    date1 = this.funcGetDay(-1, date1);
    return date1;
  },
  // 获取某一天(例如昨天或者明天)
  funcGetDay(num, dateStr = '', incTime = false) {
    let ts = this.funcGetTimestampByDate(dateStr);
    ts += num * 86400;
    return this.funcGetDateByTimestamp(ts, incTime);
  },
  // 获取某一小时(例如下一小时)
  funcGetDayAndTime(num, dateStr = '', incTime = false) {
    let ts = this.funcGetTimestampByDate(dateStr);
    ts += num * 3600;
    return this.funcGetDateByTimestamp(ts, incTime);
  },

  // 根据日期字符串取时间戳
  funcGetTimestampByDate(dateStr) {
    const d = !dateStr ? new Date() : new Date(dateStr.substr(0, 10));
    let timestamp = d.getTime();
    timestamp /= 1000;
    timestamp = parseInt(timestamp, 10);
    return timestamp;
  },

  // 根据时间戳取日期字符串
  funcGetDateByTimestamp(ts, incTime = false) {
    const tsNum = ts * 1000;
    let strDay = '';
    const tsNum2 = tsNum + '';
    if (tsNum2.length !== 13) {
      strDay = this.funcToday();
    } else {
      const d = new Date(tsNum);
      const yy = d.getFullYear();
      let mm = d.getMonth() + 1;
      let dd = d.getDate();

      mm = mm < 10 ? '0' + mm : mm;
      dd = dd < 10 ? '0' + dd : dd;
      strDay = yy + '-' + mm + '-' + dd;

      if (incTime) {
        let hh = d.getHours();
        let m2 = d.getMinutes();

        hh = hh < 10 ? '0' + hh : hh;
        m2 = m2 < 10 ? '0' + m2 : m2;

        strDay += ' ' + hh + ':' + m2;
      }
    }

    return strDay;
  },

  // 获取本周范围
  funcGetWeek(dateStr = '') {
    const d = dateStr === '' ? new Date() : new Date(dateStr);
    let week = d.getDay();
    if (week === 0) week = 7;
    week -= 1;
    let timestamp = d.getTime();
    timestamp /= 1000;
    timestamp = parseInt(timestamp, 10);
    const ts0 = timestamp - week * 86400;
    const ts1 = timestamp + (6 - week) * 86400;
    const { funcGetDateByTimestamp } = this;
    const date0 = funcGetDateByTimestamp(ts0) + ' 00:00:00';
    const date1 = funcGetDateByTimestamp(ts1) + ' 23:59:59';
    return { startDate: date0, endDate: date1 };
  },

  // 获取一个随机数(取毫秒)
  funcRand() {
    const now = new Date();
    return now.getMilliseconds();
  },

  // 格式化手机号(中间加空格)
  funcPhoneSpace(value) {
    if (value === '' || value === undefined || value == null || window.isNaN(value)) return '';
    let val2 = value;
    if (value.length >= 4) val2 = value.substr(0, 3) + ' ' + value.substr(3, 4);
    if (value.length >= 8) val2 += ' ' + value.substr(7, 4);
    return val2;
  },

  // 根据数组索引下标取数组索引下标对应的值
  funcGetArrayValueByIndex(indexStr, arr) {
    if (indexStr === '') {
      return '';
    }

    // if (indexStr.indexOf(',') <= -1){
    //     return indexStr;
    // }

    const arrIndex = indexStr.split(',');
    let arrValue = '';
    let value = '';
    for (let i = 0; i < arrIndex.length; i += 1) {
      value = arr[arrIndex[i]];
      arrValue += value;
      if (i < arrIndex.length - 1) {
        arrValue += ', ';
      }
    }
    return arrValue;
  },

  // 设置cookie
  funcSetCookie(name, value) {
    const day = 7;
    const exp = new Date();
    exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000);
    document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
  },
  // 获取cookie
  funcGetCookie(name) {
    if (document.cookie.length > 0) {
      let start = document.cookie.indexOf(name + '=');
      if (start >= 0) {
        start = start + name.length + 1;
        let end = document.cookie.indexOf(';', start);
        if (end === -1) end = document.cookie.length;
        return unescape(document.cookie.substring(start, end));
      }
    }
    return '';
  },
  // 删除cookie
  funcDelCookie(name) {
    const exp = new Date();
    exp.setTime(exp.getTime() - 1);
    const cval = this.funcGetCookie(name);
    if (cval != null) document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString();
  },

  // 获取本地存储的值
  funcGetLocalValue(name) {
    return sessionStorage.getItem(name) || '';
  },
  // 把值写入本地存储
  funcSetLocalValue(name, value) {
    sessionStorage.setItem(name, value);
  },
  // 获取访问令牌
  funcGetToken() {
    return this.funcGetLocalValue('token') || 'a';
  },
  // 获取用户ID
  funcGetUserId() {
    return parseInt(this.funcGetLocalValue('userId') || '1', 10);
  },
  // 检查访问令牌
  funcCheckToken() {
    const token = this.funcGetToken();
    const userId = this.funcGetUserId();
    let ok = true;

    if (token.length !== 88) ok = false;
    if (token.substr(token.length - 2, 2) !== '==') ok = false;
    if (window.isNaN(userId)) ok = false;

    const result = {
      success: ok,
    };
    if (ok) {
      result.userId = userId;
      result.token = token;
    }
    return result;
  },

  // 获取网络请求的具体api接口名称
  funcGetApiName() {
    let path = window.location.href;
    path = path.substr(path.lastIndexOf('/') + 1, path.length);
    return path;
  },

  // 获取对象成员个数
  funcGetObjNum(obj) {
    let count = 0;
    for (const i in obj) {
      count += 1;
    }
    return count;
  },

  // 对话框的标题带图标
  funcDlgTitle(title, act, appendInfo) {
    let type = 'file-add';
    let stat = '新增';
    let info = '信息';
    if (act === 'edit') {
      type = 'edit';
      stat = '编辑';
    }
    if (!appendInfo) info = '';

    return (
      <div>
        <Icon type={type} style={{ fontSize: 18 }} />
        <span> {stat + title + info}</span>
      </div>
    );
  },
  // 对话框的保存按钮
  funcDlgBtnSave(text = '保存', type = 'cloud-upload', size = 18) {
    return (
      <div>
        <Icon type={type} style={{ fontSize: size }} />
        <span> {text}</span>
      </div>
    );
  },
  // 对话框的取消按钮
  funcDlgBtnCancel(text = '取消') {
    return (
      <div>
        <Icon type="close" />
        <span> {text}</span>
      </div>
    );
  },

  // 克隆对象
  funcClone(obj) {
    let o;
    if (typeof obj === 'object') {
      if (obj === null) {
        o = null;
      } else {
        if (obj instanceof Array) {
          o = [];
          for (let i = 0, len = obj.length; i < len; i += 1) {
            o.push(this.funcClone(obj[i]));
          }
        } else {
          o = {};
          for (const j in obj) {
            o[j] = this.funcClone(obj[j]);
          }
        }
      }
    } else {
      o = obj;
    }
    return o;
  },

  // 获取文本输入框的文字内容
  funcGetInputValue(id) {
    return document.getElementById(id).value;
  },

  // 封装service层(为了减少代码量)
  funcReq(path, params, needGetStatus = 0, needReadText = 0, anyRequest = 0, reqType = 'json') {
    const basicUrl = anyRequest ? '' : netUrl();
    return request(
      basicUrl + path,
      {
        method: 'POST',
        body: params,
      },
      needGetStatus,
      needReadText,
      reqType
    );
  },

  // 修正小数的同时还可附带单位(unit)
  funcFixNum(num, digit = 1, unit = '') {
    const digits = {
      1: 10,
      2: 100,
      3: 1000,
      4: 10000,
    };
    if (window.isNaN(num)) return num;
    const n = Math.round(num * digits[digit]) / digits[digit];
    return unit === '' ? n : n + unit;
  },

  // 判断是否是IE浏览器
  funcIsIE() {
    let isIE = navigator.userAgent.indexOf('MSIE') >= 1;
    if (!isIE) isIE = navigator.userAgent.indexOf('Trident') >= 1;
    return isIE;
  },

  // 获取本地静态文件(图片)的完整访问地址
  funcUrl(file) {
    let url = window.location.origin;
    if (process.env.NODE_ENV === 'development') {
      // 开发环境
      url += file;
    } else {
      // 生产环境
      let url2 = window.location.pathname;
      if (url2 !== '/') {
        url2 = url2.substr(0, url2.lastIndexOf('/'));
      }
      url += url2 + file;
    }
    return url;
  },

  // 获取页面的完整访问地址
  funcUrlDynamic(path) {
    if (process.env.NODE_ENV === 'development') {
      // 开发环境
      return tools.funcUrl(path);
    }

    // 生产环境
    let url = window.location.origin;
    const url2 = window.location.pathname;
    url += url2 + '#' + path;
    return url;
  },

  // 判断当前访问页面的是电脑还是手机或是平板
  funcGetDevice() {
    const ua = navigator.userAgent,
      isWindowsPhone = /(?:Windows Phone)/.test(ua),
      isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
      isAndroid = /(?:Android)/.test(ua),
      isFireFox = /(?:Firefox)/.test(ua),
      isTablet =
        /(?:iPad|PlayBook)/.test(ua) ||
        (isAndroid && !/(?:Mobile)/.test(ua)) ||
        (isFireFox && /(?:Tablet)/.test(ua)),
      isPhone = /(?:iPhone)/.test(ua) && !isTablet,
      isPc = !isPhone && !isAndroid && !isSymbian;
    const arr = [isPc, isPhone, isTablet];
    const arr2 = ['电脑', '手机', '平板'];
    let device = arr2[0];
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i]) device = arr2[i];
    }
    return device;
  },

  // 查询条件转换, 查询数组转对象
  funcSearchArrayToObject(arr) {
    const obj = {};
    arr.map(row => {
      const { name, value, searchType } = row;
      if (searchType === 'EQ') obj[name] = value;
      else {
        if (searchType === 'GT' && value.indexOf(' 00:00:00') === 10) obj['beginDate'] = value;
        else if (searchType === 'LT' && value.indexOf(' 23:59:59') === 10) obj['endDate'] = value;
      }
    });
    return obj;
  },
};
export default tools;
